/*****************************************************************
 * this program performs that it reverse a string by words,for example,
 *
 * string = "Hello World This is C Programming";
 * ReverseWors(string);
 * string = "Programming C is This World Hello";
 *
 * date:	2015|11|23
 * author:	laishaofa@gmail.com
 *****************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void ReverseWords(char* str);

int main()
{
    char str[] = "Hello World This is C Programming";

    printf("Original Words:\t%s\n",str);
    ReverseWords(str);
    printf("Reversed Words:\t%s\n",str);

    return 0;
}

void ReverseWords(char* str)
{
    int len = strlen(str);
    int i = 0;
    char *tmpstr = (char*)malloc(len+1);
    char *head = NULL;
    char *tail = NULL;
    head = tail = str+len;

    memset(tmpstr, 0, len+1);

    while(i++<len)
    {
        head--;
        if(*head == ' ')
        {
            head++;
            strcat(tmpstr,head);
            strcat(tmpstr," ");
            head--;
            tail = head;
            *tail = '\0';
        }
    }
    strcat(tmpstr,head);
    strcpy(str, tmpstr);
}
